<div class="row-fluid clearfix">
    <div class="col-md-12 column">
        <ul class="breadcrumb">
            <li>
                <a href="index.html">首页</a>
            </li>
            <li class="active">
                数据字典管理
            </li>
        </ul>
    </div>
    <div class="col-md-12 column">
        <div class="col-sm-12 div-page">
            <div class="col-sm-12 div-table">
                <div id="custom-toolbar">
                </div>
                <table id="table" class="table table-hover table-condensed" data-toolbar="#custom-toolbar"
                       data-click-to-select="true"  data-single-select="true" data-height="450">
                    <thead>
                    <tr>
                        <th class="col-sm-1" data-field="state" data-checkbox="true" ></th>
                        <th class="col-sm-4" data-field="Dic_name_tree" data-halign="left" data-align="left" data-events="operateEvents">字典名称</th>
                        <th data-visible="false" data-field="Dic_name" data-halign="center" data-align="center" >字典名称</th>
                        <th data-visible="false" data-field="Dic_type" data-halign="center" data-align="center">字典类型</th>
                        <th class="col-sm-3" data-field="Dic_data" data-halign="center" data-align="center">字典编码</th>
                        <th class="col-sm-2" data-field="Dic_note" data-halign="center" data-align="center">备注</th>
                        <th class="col-sm-2" data-field="Dic_sort" data-halign="center" data-align="center">排序</th>
                    </tr>
                    </thead>
                </table>
            </div>
        </div>
        <div class="col-sm-12 alert alert-success div-alert" id="events-result" data-es="Aquí se muestra el resultado del evento"></div>
        <!-- #遮罩层 --->
        <div class="modal fade" id="modal-DataEdit" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
            <div class="modal-dialog modal-lg">
                <div class="modal-content">
                    <div class="modal-header">
                        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
                        <div class="modal-title" id="myModalLabel">
                            数据字典管理
                        </div>
                    </div>
                    <form id="validForm" name="validForm" method="post" class="form-horizontal layer_msg">
                        <input type="hidden" id="actionType" name="actionType" />
                        <input type="hidden" id="Dic_cflag" name="Dic_cflag" />
                        <input type="hidden" id="Dic_printer" name="Dic_printer" />
                        <input type="hidden" id="Dic_data" name="Dic_data" />

                        <div class="modal-body">
                            <div class="row-fluid">
                                <div class="col-sm-6 form-group">
                                    <label class="col-sm-4 control-label">字典类型</label>
                                    <div class="col-sm-8">
                                        <input type="text" class="form-control" id="Dic_type" name="Dic_type" placeholder=""
                                               readonly />
                                    </div>
                                </div>
                                <div class="col-sm-6 form-group hidden">
                                    <label class="col-sm-4 control-label">父字典名称</label>
                                    <div class="col-sm-8">
                                        <input type="text" class="form-control" id="Dic_name_P" name="Dic_name_P" placeholder=""
                                               readonly />
                                    </div>
                                </div>
                            </div>
                            <div class="row-fluid">
                                <div class="col-sm-6 form-group">
                                    <label class="col-sm-4 control-label">字典编码</label>
                                    <div class="col-sm-8">
                                        <input type="text" class="form-control" id="Dic_data_new" name="Dic_data_new" placeholder=""
                                               required  data-fv-notempty-message="请输入" />
                                    </div>
                                </div>
                                <div class="col-sm-6 form-group">
                                    <label class="col-sm-4 control-label">字典名称</label>
                                    <div class="col-sm-8">
                                        <input type="text" class="form-control" id="Dic_name" name="Dic_name" placeholder=""
                                               required  data-fv-notempty-message="请输入" />
                                    </div>
                                </div>
                            </div>
                            <div class="row-fluid">
                                <div class="col-sm-6 form-group">
                                    <label class="col-sm-4 control-label">备注</label>
                                    <div class="col-sm-8">
                                        <input type="text" class="form-control" id="Dic_note" name="Dic_note" placeholder=""
                                                />
                                    </div>
                                </div>
                                <div class="col-sm-6 form-group">
                                    <label class="col-sm-4 control-label">排序</label>
                                    <div class="col-sm-8">
                                        <input type="text" class="form-control" id="Dic_sort" name="Dic_sort" placeholder=""
                                                />
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div class="modal-footer">
                            <button id="modal-btn-save" type="submit" class="btn btn-primary">保存</button>
                            <button id="modal-btn-del" type="button" class="btn btn-danger">确认删除</button>
                            <button id="modal-btn-close" type="button" class="btn btn-default" data-dismiss="modal">关闭</button>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>


<script>

$(function(){
    //绑定列自定义事件
    window.operateEvents = {
        'click span': function (e, value, row, index) {
            opTree($("#table tbody ").find("tr").eq(index),"");
        }
    };

    ///获取role按钮权限
    var btnHtml ;
    var btnRole = JSON.parse($.cookie("Role_note"));

    btnHtml = '<div class="form-inline" role="form">';
    btnHtml += (btnRole["CommonDataAdd"]) ? '<button id="btn-CommonDataAdd"  type="button" role="button" class="btn btn-sm btn-Data btn-primary">' +
            '<span class="glyphicon glyphicon-plus"></span> 新增</button> ' : '' ;
    btnHtml += (btnRole["CommonDataModify"]) ? '<button id="btn-CommonDataModify" type="button" role="button" class="btn btn-sm btn-Data btn-success disabled">' +
            '<span class="glyphicon glyphicon-pencil"></span> 修改</button> ' : '' ;
    btnHtml += (btnRole["CommonDataCancel"]) ? '<button id="btn-CommonDataCancel"  type="button" role="button" class="btn btn-sm btn-Data btn-danger disabled" >' +
            '<span class="glyphicon glyphicon-trash"></span> 删除</button> ' : '' ;

    $("#custom-toolbar").append(btnHtml);

    $('#table').bootstrapTable({
        url: globalUrl+'api/Dict',
        responseHandler:function(resp){
            var dataSet=[];
            GetTreeDictData(dataSet,0,resp.data);
            return dataSet;
        },
        pagination:false,
        pageSize:5,
        search:true,
        pageList:[1,5,10]
    })
            .on('check.bs.table', function (e, row) {
                //$("#events-result").text('Event: check.bs.table, data: ' + JSON.stringify(row));
                $(".btn-Data").removeClass("disabled");
                if(row["Dic_type"]!="0000000000"){
                    $("#btn-CommonDataAdd").addClass("disabled");
                }else{
                    $("#btn-CommonDataAdd").removeClass("disabled");
                }
                if(row["_class"]=="level1 hasChild" || row["_class"]=="level1 hasChild selected info"){
                    $("#btn-CommonDataCancel").addClass("disabled");
                }
                else{
                    $("#btn-CommonDataCancel").removeClass("disabled");
                }
            })
            .on('uncheck.bs.table', function (e, row) {
                //$("#events-result").text('Event: uncheck.bs.table, data: ' + JSON.stringify(row));
                $(".btn-Data").addClass("disabled");
                $("#btn-CommonDataAdd").removeClass("disabled");
            })


///弹出层验证，submit时生效
    $('#validForm')
            .formValidation({
                message: 'This value is not valid',
                icon: {
                    valid: 'glyphicon glyphicon-ok',
                    invalid: 'glyphicon glyphicon-remove',
                    validating: 'glyphicon glyphicon-refresh'
                }
            })
            .on('success.form.fv', function(e) {
                e.preventDefault();
                var $form = $(e.target);
                var bv = $form.data('formValidation');
                if($('#validForm').find(' input[name="actionType"] ').val()=="edit"){
                    // Use Ajax to submit form data
                    $('#validForm').find(' input[name="Dic_data_new"] ').val($('#validForm').find(' input[name="Dic_data"] ').val());
                    var data = JsonToRow($form);
                    //alert(JSON.stringify(data));
                    $.ajax({
                        data:data,
                        type: "put",
                        url: globalUrl+"api/Dict",
                        dataType: "json",
                        success: function (resp) {
                            //alert(JSON.stringify(resp));
                            if(resp.result)
                            {
                                //$("#events-result").text('Send data: ' + $form.serialize());
                                //$("#events-result").text('Send data: create site ok');
                                dataBindToDictTable($('#table'),$('#validForm'));

                                //关闭弹出窗口
                                $('#modal-DataEdit').modal('hide');
                            }
                            else
                            {
                                alert(JSON.stringify(resp));
                            }
                        },
                        error:function(){
                            alert("插入数据失败！");
                        }
                    });
                }else if($('#validForm').find(' input[name="actionType"] ').val()=="add"){
                    $("#Dic_data").val($("#Dic_data_new").val());
                    var data = JsonToRow($form);
                    $.ajax({
                        data:data,
                        type: "post",
                        url: globalUrl+"api/Dict",
                        dataType: "json",
                        success: function (resp) {
                            if(resp.result)
                            {
                                dataAddToDictTable($('#table'),$('#validForm'));
                                $('#btn-CommonDataCancel').addClass("disabled");
                                //关闭弹出窗口
                                $('#modal-DataEdit').modal('hide');
                            }
                            else
                            {
                                alert(JSON.stringify(resp));
                            }
                        },
                        error:function(){
                            alert("插入数据失败！");
                        }
                    });
                }else{

                }

            });

});

///表格事件/////////////////////////////////////////////////////
//获得树表数据
function GetTreeDictData(myData,j,dataObj) {
    var len = dataObj.length;
    var k = j-1 ;
    for(var i=0;i<len;i++)
    {
        var _tmpData = {};
        _tmpData["Dic_type"] = dataObj[i].Dic_type ;
        _tmpData["Dic_name_tree"] = '<span></span> '+dataObj[i].Dic_name ;
        _tmpData["Dic_name"] = dataObj[i].Dic_name ;
        _tmpData["Dic_data"] = dataObj[i].Dic_data ;
        _tmpData["Dic_note"] = dataObj[i].Dic_note ;
        _tmpData["Dic_sort"] = dataObj[i].Dic_sort ;
        _tmpData["_id"] = j;
        _tmpData["_pid"] = k;
        _tmpData["_class"] = (_tmpData["Dic_type"]=="0000000000") ? 'level1 child' : 'level2 child';
        _tmpData["_state"] = 'Expand';
        myData[j] = _tmpData;
        j++;
        if( dataObj[i].hasOwnProperty( "children" ) ){
            if(dataObj[i].children.length>0){
                myData[j-1]["_class"]= (myData[j-1]["Dic_type"]=="0000000000") ? 'level1 hasChild' : 'level2 hasChild';
                j = arguments.callee(myData,j,dataObj[i].children);
            }
        }
    }
    return j;
}
//添加节点，重建树表
function dataAddToDictTable(_obj,_sourceObj){
    var _tmpData = {};
    var _tableObj = JsonToRow(_sourceObj);
    //alert(JSON.stringify(_tableObj));
    _tmpData["Dic_type"] = _tableObj.Dic_type ;
    _tmpData["Dic_name_tree"] = '<span></span> '+_tableObj.Dic_name ;
    _tmpData["Dic_name"] = _tableObj.Dic_name ;
    _tmpData["Dic_data"] = _tableObj.Dic_data ;
    _tmpData["Dic_note"] = _tableObj.Dic_note ;
    _tmpData["Dic_sort"] = _tableObj.Dic_sort ;
    _tmpData["_id"] = _obj.find(' tbody > tr ').length;
    _tmpData["_pid"] = (_obj.bootstrapTable('getSelections').length>0) ? _obj.find(' tbody > tr.selected ').attr("id") : "-1";
    _tmpData["_class"] = (_tmpData["Dic_type"]=="0000000000") ? 'level1 child' : 'level2 child';
    _tmpData["_state"] = 'Expand';

    //alert(JSON.stringify(_tmpData));

    var tableData = _obj.bootstrapTable('getData');
    var dataArray = new Array();
    var dataArrayLeft = new Array();
    var dataArrayRight = new Array();
    var dataArrayMiddle = new Array();

    var index = tableData.length-1;
    //更新父节点显示
    if(_obj.bootstrapTable('getSelections').length>0){
        //_obj.bootstrapTable('getSelections')[0]["_class"] = ' level1 hasChild info ' ;
        _obj.bootstrapTable('getSelections')[0]["_class"] = 'level1 hasChild' ;
        index = GetTreeLastNode(_obj.find(' tbody > tr.selected '));
    }

    //alert(index);
    for(var i=0;i<=index;i++){
        dataArrayLeft[i] = tableData[i];
    }
    for(var i=0;i<tableData.length-parseInt(index)-1;i++){
        dataArrayRight[i] = tableData[i+parseInt(index)+1];
    }
    //alert(dataArrayLeft);
    dataArrayMiddle[0] = _tmpData;
    var dataArray = dataArrayLeft.concat(dataArrayMiddle.concat(dataArrayRight));
    //alert(dataArray);
    _obj.bootstrapTable("load", dataArray);
}

//刷新行数据
function dataBindToDictTable(_obj,_sourceObj){
    var _tmpData = {};
    var _index = _obj.find("tr.selected").index();
    var _tableObj = JsonToRow(_sourceObj);
    //alert(JSON.stringify(_tableObj));
    _tmpData["Dic_type"] = _tableObj.Dic_type ;
    _tmpData["Dic_name_tree"] = '<span></span> '+_tableObj.Dic_name ;
    _tmpData["Dic_name"] = _tableObj.Dic_name ;
    _tmpData["Dic_data"] = _tableObj.Dic_data ;
    _tmpData["Dic_note"] = _tableObj.Dic_note ;
    _tmpData["Dic_sort"] = _tableObj.Dic_sort ;
    _tmpData["_id"] = _obj.find(' tbody > tr.selected ').attr("id") ;
    _tmpData["_pid"] =  _obj.find(' tbody > tr.selected ').attr("pid") ;
    _tmpData["_class"] = _obj.find(' tbody > tr.selected ').attr("class") ;
    _tmpData["_state"] = 'Expand';
    //_tmpData["state"] = false;

    //alert(JSON.stringify(_row));
    _obj.bootstrapTable('updateRow', {
        index: _index,
        row: _tmpData
    });
}

function GetLevelClass(index){
    var organLevelClass = ['level1','level2','level3','level4'];
    resp = organLevelClass[parseInt(index)-1];
    return resp;
}

//新增按钮
$('#btn-CommonDataAdd').on("click",function () {

    var Dic_type = "0000000000";
    dataBindToModal($('#validForm'),null);
    $('#validForm').find(' input[name="actionType"] ').val("add");
    if($('#table').bootstrapTable('getSelections').length>0){
        Dic_type = $('#table').bootstrapTable('getSelections')[0]["Dic_data"];
    }
    $('#validForm').find(' input[name="Dic_type"] ').val(Dic_type);
    $('#modal-btn-del').addClass('hidden');
    $('#modal-btn-save').removeClass('hidden');
    $("#Dic_data_new").attr("readonly",false);
    $('#modal-DataEdit').modal('show');
});
//编辑按钮数据传递
$('#btn-CommonDataModify').on("click",function () {

    dataBindToModal($('#validForm'),$('#table'));
    //$('#validForm').find(' input[name="Dic_data_new"] ').val("edit");
    $("#Dic_data_new").val($("#Dic_data").val()).attr("readonly","readonly");
    $('#validForm').find(' input[name="actionType"] ').val("edit");
    //$("#events-result").text('Selected values: ' + JSON.stringify($('#validForm').serializeArray()));
    $('#modal-btn-del').addClass('hidden');
    $('#modal-btn-save').removeClass('hidden');
    $('#modal-DataEdit').modal('show');
});
//删除按钮
$('#btn-CommonDataCancel').on("click",function () {

    dataBindToModal($('#validForm'),$('#table'));
    $("#Dic_data_new").val($("#Dic_data").val()).attr("readonly",true);

    //$("#events-result").text('Selected values: ' + JSON.stringify($('#validForm').serializeArray()));
    $('#modal-btn-del').removeClass('hidden');
    $('#modal-btn-save').addClass('hidden');
    $('#modal-DataEdit').modal('show');
});

///弹出层事件/////////////////////////////////////////////////////
//弹出层关闭时重置valid域
$('#modal-DataEdit').on("hide.bs.modal",function () {
    $('#validForm').data('formValidation').resetForm();
    if($('#table').bootstrapTable('getSelections').length==0){
        $(".btn-Data").addClass("disabled");
    }

});

//删除
$('#modal-btn-del').on("click",function () {

    //$("#events-result").text('Selected values: ' + $('#validForm').serialize());

    var data = $('#validForm').serialize();
    //alert(JSON.stringify(date));
    $.ajax({
        type: "delete",
        data: "",
        dataType: "json",
        url: globalUrl+"api/Dict?"+data,
        success: function (resp) {
            //alert(JSON.stringify(resp));
            if(resp.result)
            {
                //$("#events-result").text('Send data: ' + $('#validForm').serialize());
                dataDelFromTable($('#table'));
                $("#btn-CommonDataAdd").removeClass("disabled");
                //关闭弹出窗口
                $('#modal-DataEdit').modal('hide');
            }
            else
            {
                alert(JSON.stringify(resp));
            }
        },
        error:function(){
            alert("更新数据失败！");
        }
    });
});

</script>

<!-- /自定义脚本 -->



